import Vue from 'vue'
import VueRouter from 'vue-router'
import { routes_root } from "./routes/root";
import { routes_test } from "./routes/test";
import { routes_store } from "./routes/store";
import { routes_items } from "./routes/items";
import { routes_last } from "./routes/root_last";
import { routes_other } from "./routes/other";
import { routes_user } from "./routes/user";
import { routes_order } from "./routes/order";
import { routes_act } from "./routes/act";

import RefreshInterceptor from "./interceptor/RefreshInterceptor";
import InfoInterceptor from "./interceptor/InfoInterceptor";
import LinkInterceptor from "./interceptor/LinkInterceptor";
import ParamsInterceptor from "./interceptor/ParamsInterceptor";

/*这里加这一段是因为router.push 只改变query不改变path的话会报错,可以优化为子路由的形式*/
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push (location) {
    return originalPush.call(this, location).catch(err => err)
}
Vue.use(VueRouter);


// 定义路由
// 每个路由应该映射一个组件。 其中"component"是一个组件配置对象。

const routes = routes_root.concat(routes_test).concat(routes_last).concat(routes_other)
    .concat(routes_user).concat(routes_items).concat(routes_store).concat(routes_order)
    .concat(routes_act);

let router = new VueRouter({
    mode: 'history',
    routes
});
//路由拦截
router.beforeEach((to, from, next) => {
    LinkInterceptor.addTtn(to, from);
    if (LinkInterceptor.redirectedURLFn(to, next)) {
        next();
        return
    }
    if (LinkInterceptor.isBreak(to, next)) {
        next();
        return
    }

    if (LinkInterceptor.isPreview(to, next)) {
        next();
        return
    }
    if (LinkInterceptor.isPreviewController(to, next)) {
        next();
        return
    }

    if (LinkInterceptor.toLogin(to, next)) {
        next();
        return
    }
    //更新preview状态
    RefreshInterceptor.refreshPreview(to);
    // --------!!拦截顺序有讲究！不可随意更改！！-----------------/
    RefreshInterceptor.refreshCookieUser();
    ParamsInterceptor.refreshRecommender(to);

    //这里给第三方授权登录
    if (LinkInterceptor.toThirdAuth(to, next)
        || LinkInterceptor.payReturn(to, next)) {
        return
    }
    RefreshInterceptor.refreshNextPage(to, from);

    RefreshInterceptor.refreshShareInfo();
    if (InfoInterceptor.userAuth(to, next)
        || InfoInterceptor.thirdAuth(to, next) || InfoInterceptor.userOrThird(to, next)) {
        return
    }
    next();
});
export default router
